﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using jqwidgetsapi.Models;

namespace jqwidgetsapi.Models
{
    public class SeriesRepository : ISeriesRepository
    {
        private List<Series> seriescollection = new List<Series>();
        private short _nextId = 1;

        public SeriesRepository()
        {
            var csv_rep = new CsvRepository();
            seriescollection = csv_rep.returnAll();
        }

        public bool TryGet(short id, out Series item)
        {
            Dictionary<short, Series> dictionary =
                      seriescollection.ToDictionary(p => p.Id);

            return dictionary.TryGetValue(id, out item);
        }

        public IEnumerable<Series> GetAll()
        {
            return seriescollection;
        }

        public Series Get(short id)
        {
            return seriescollection.Find(p => p.Id == id);
        }

        public IEnumerable<Series> GetLimit(short page, short rows)
        {
            var offset = (page - 1) * rows;
            return seriescollection.Take(rows).Skip(offset);
        }

        public Series Add(Series item)
        {
            item.Id = _nextId++;
            seriescollection.Add(item);
            return item;
        }

        public void Remove(short id)
        {
            seriescollection.RemoveAll(p => p.Id == id);
        }

        public bool Delete(short id)
        {
            Dictionary<short, Series> dictionary =
                   seriescollection.ToDictionary(p => p.Id);
            seriescollection.RemoveAll(p => p.Id == id);

            return dictionary.Remove(id);
        }

        public bool Update(Series item)
        {
            int index = seriescollection.FindIndex(p => p.Id == item.Id);
            if (index == -1)
            {
                return false;
            }
            //we're going to update only the name and the description
            var single = seriescollection[index];
            single.Name = item.Name;
            single.Description = item.Description;
            seriescollection.RemoveAt(index);

            seriescollection.Add(single);
            return true;
        }
    }
}
